import { wxLogin, login } from '@/api/user'
const state = {
  hasLogin: false,
  userInfo: uni.getStorageSync('userinfo'),
  access_token: uni.getStorageSync('token'),
  sessionInfo: uni.getStorageSync('sessionInfo'),
  roleType: uni.getStorageSync('roleType'),
}

const mutations = {
  SET_ROLETYPE: (state, data) => {
    state.roleType = data;
    uni.setStorage({//将用户角色保存在本地  
      key: 'roleType',
      data: data
    })
  },
  SET_SESSIONINFO: (state, data) => {
    state.sessionInfo = data;
    uni.setStorage({//将用户信息保存在本地  
      key: 'sessionInfo',
      data: data
    })
  },
  SET_ACCESS_TOKEN: (state, data) => {
    state.hasLogin = true;
    state.access_token = data;
    uni.setStorage({//将用户信息保存在本地  
      key: 'token',
      data: data
    })
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data;
    uni.setStorage({//将用户信息保存在本地  
      key: 'userinfo',
      data: data
    })
  },
  LOGOUT: (state) => {
    state.hasLogin = false;
    state.userInfo = {};
    state.sessionInfo = {};
    uni.clearStorage()
  }
}

const actions = {
  async wxLogin({ dispatch }) {
    try {
      await dispatch('setLoginInfo')
      uni.redirectTo({ url: "/pages/main/index" });
    } catch (err) {
      uni.showToast({
        title: '登录失败',
        icon: 'error'
      })
    }

  },
  async login({ commit, state }, provider) {
    // let encodeUsername=await encrypt(provider.userName)
    // let encodePassword=await encrypt(provider.password)
    // console.log('encodeUsername',encodeUsername);
    // console.log('encodePassword',encodePassword);
    const { data } = await login({
      phone: provider.phone,
      code: provider.code,
    })
    console.log('logindata',data);
    if (data.token ) {
      uni.$u.toast("登录成功！");
      commit('SET_ACCESS_TOKEN', data.token)
      commit('SET_USERINFO', data)
      uni.switchTab({ url: "/pages/home/index" });
    }
  },
  setLoginInfo({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      try {
        console.log('state.sessionInfo',state.sessionInfo);
        const data = await wxLogin(state.sessionInfo)
        if (data.data ) {
          commit('SET_ACCESS_TOKEN', data.data.token)
          commit('SET_USERINFO', data.data)
          resolve()
        }
         else {
          reject()
        }
      } catch (err) {
        if (err.code === 404) {
          uni.navigateTo({ url: '/login/other' })
        }
      }
    })
  },
  logout({ commit }) {
    commit('LOGOUT')
  }
}

export default {
  state,
  mutations,
  actions
}
